package cn.stalk.wf.service.impl;

import cn.stalk.wf.service.AccessService;
import cn.stalk.wf.service.FlowService;
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.task.IdentityLink;
import org.camunda.bpm.engine.task.IdentityLinkType;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.instance.RootElement;
import org.camunda.bpm.model.bpmn.instance.UserTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class FlowServiceImpl implements FlowService {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;

    @Autowired
    private AccessService accessService;

    @Override
    public Collection<UserTask> parseUserTasks(String processDefinitionId) {
        BpmnModelInstance instance = repositoryService.getBpmnModelInstance(processDefinitionId);
        Collection<RootElement> rootElements = instance.getDefinitions().getRootElements();

        Set<UserTask> userTasks = new HashSet<>();
        for (RootElement rootElement : rootElements) {
            userTasks.addAll(rootElement.getChildElementsByType(UserTask.class));
        }


        return userTasks;
    }

    /**
     * 查询任务候选人
     */
    @Override
    public Set<String> selectTaskCandidate(String taskId) {
        List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(taskId);

        Set<String> userList = new HashSet<String>();
        identityLinks.stream().filter(e -> IdentityLinkType.CANDIDATE.equals(e.getType())).forEach(e -> {
            if (StringUtils.isNotBlank(e.getUserId())) {
                userList.add(e.getUserId());
            } else if (StringUtils.isNotBlank(e.getGroupId())) {
                userList.addAll(accessService.selectUserByGroup(e.getGroupId()));
            }
        });

        return userList;
    }

}
